package com.starsoft.trade.web;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.starsoft.frame.base.service.UserService;
import com.starsoft.frame.core.web.WebUtil;
import com.starsoft.frame.util.DateUtil;
import com.starsoft.smdc.service.HolidayService;
import com.starsoft.trade.bean.TradeAcount;
import com.starsoft.trade.bean.TradeAcountStatus;
import com.starsoft.trade.bean.TradeBill;
import com.starsoft.trade.service.AcountStatusService;
import com.starsoft.trade.service.TradeAcountService;
import com.starsoft.trade.service.TradeBillService;
import com.starsoft.trade.trader.TraderService;

//@Controller
//@RequestMapping(value = "/trade/synch")
public class AcountSynchController {

	@Autowired
	private AcountStatusService acountStatusService;
	
	@Autowired
	private HolidayService holidayService;
	
	@Autowired
	TraderService traderService;
	
	@Autowired
	TradeAcountService tradeAcountService;
	
	@Autowired
	TradeBillService billService;
	
	@RequestMapping(value="/getstatus")
	public ModelMap getStatus(HttpServletRequest request, ModelMap model){
		Integer acountId = UserService.getUserContext().getAcountId();
		TradeAcountStatus status = acountStatusService.updateAndGetLatest(acountId);
		return model.addAllAttributes(acountStatusService.convertBean(status));
	}
	
	@RequestMapping(value="/getexstatus")
	public ModelMap getStatusEx(HttpServletRequest request, ModelMap model){
		TradeAcount acount =tradeAcountService.get(UserService.getUserContext().getAcountId());
		TradeAcountStatus status = traderService.getPortfoil(acount);
		return model.addAllAttributes(acountStatusService.convertBean(status));
	}
	
	@RequestMapping(value="/synchbill")
	public ModelMap synchBill(HttpServletRequest request, ModelMap model){
		TradeAcount acount =tradeAcountService.get(UserService.getUserContext().getAcountId());
		Date startDate = WebUtil.getDate(request, "startDate", "yyyy-MM-dd");
		if(startDate==null){
			startDate = billService.getLastBillDate(acount.getAcountId());
			if(startDate!=null){
				startDate = DateUtil.getNext(startDate);
			}
		}
		if(startDate==null){
			startDate = acount.getInitDate();
			startDate = DateUtil.getNext(startDate);
		}
		List<TradeBill> bills = traderService.synchBill(acount, startDate);
		return model.addAttribute("rows", bills);
	}
}
